package cn.itcast.chapter08.filter;

import cn.itcast.chapter08.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "LoginServlet", urlPatterns = "/LoginServlet")

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if("itcast".equals(username)&&"123456".equals(password)){
            //登录成功
            //将用户状态user对象存入session域
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            request.getSession().setAttribute("user",user);
            //发送自动登录的cookie
            String autoLogin = request.getParameter("autologin");
            if(autoLogin!=null){
                //注意cookie中的密码要加密
                Cookie cookie = new Cookie("autologin",username+"-"+password);
                cookie.setMaxAge(-1);
                cookie.setPath(request.getContextPath());
                response.addCookie(cookie);
            }
            //跳转至首页
            response.sendRedirect(request.getContextPath()+"/index.jsp");
        }else {
            request.setAttribute("","用户名或密码错误");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}